package org.jeecg.modules.registerRefoundAudit.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.swaggerbootstrapui.io.ResourceUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.modules.doctor.entity.DoctorRegisterRecord;
import org.jeecg.common.modules.doctor.service.IDoctorRegisterRecordService;
import org.jeecg.common.modules.register.entity.RegisterPayOrder;
import org.jeecg.common.modules.register.service.IRegisterPayOrderService;
import org.jeecg.common.modules.registerRefoundAudit.entity.RegisterRefoundAudit;
import org.jeecg.common.modules.registerRefoundAudit.service.IRegisterRefoundAuditService;
import org.jeecg.common.modules.wx.entity.WxUserinfo;
import org.jeecg.common.modules.wx.service.IWxUserinfoService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.enums.RegisterEnum;
import org.jeecg.common.wx.WxRefundService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.weixin4j.pay.WeixinPayException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.Transient;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 * @Description: 退款审核
 * @Author: jeecg-boot
 * @Date: 2021-09-29
 * @Version: V1.0
 */
@Api(tags = "退款审核")
@RestController
@RequestMapping("/registerRefoundAudit/registerRefoundAudit")
@Slf4j
public class RegisterRefoundAuditController extends JeecgController<RegisterRefoundAudit, IRegisterRefoundAuditService> {
    @Autowired
    private IRegisterRefoundAuditService registerRefoundAuditService;
    @Resource
    private IRegisterPayOrderService registerPayOrderService;
    @Resource
    private IDoctorRegisterRecordService doctorRegisterRecordService;
    @Resource
    private IWxUserinfoService wxUserinfoService;
    @Resource
    private WxRefundService wxRefundService;

    /**
     * 分页列表查询
     *
     * @param registerRefoundAudit
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "退款审核-分页列表查询")
    @ApiOperation(value = "退款审核-分页列表查询", notes = "退款审核-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(RegisterRefoundAudit registerRefoundAudit,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<RegisterRefoundAudit> queryWrapper = QueryGenerator.initQueryWrapper(registerRefoundAudit, req.getParameterMap());

        //运营审批realname 0-申请退款，1-运营审核同意，2-运营审核驳回，3-财务审核通过，4-财务审核驳回，5-完成退款

        if (sysUser.getRealname().equals("运营")) {
            queryWrapper.ne("status", 3);
        } else if (sysUser.getRealname().equals("财务")) {
            queryWrapper.in("status", 1,3, 4, 5);
        }

        Page<RegisterRefoundAudit> page = new Page<RegisterRefoundAudit>(pageNo, pageSize);
        IPage<RegisterRefoundAudit> pageList = registerRefoundAuditService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param registerRefoundAudit
     * @return
     */
    @AutoLog(value = "退款审核-添加")
    @ApiOperation(value = "退款审核-添加", notes = "退款审核-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody RegisterRefoundAudit registerRefoundAudit) {
        registerRefoundAudit.setStatus(0);
        registerRefoundAuditService.save(registerRefoundAudit);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param registerRefoundAudit
     * @return
     */
    @AutoLog(value = "退款审核-编辑")
    @ApiOperation(value = "退款审核-编辑", notes = "退款审核-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody RegisterRefoundAudit registerRefoundAudit) {
        registerRefoundAuditService.updateById(registerRefoundAudit);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "退款审核-通过id删除")
    @ApiOperation(value = "退款审核-通过id删除", notes = "退款审核-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        registerRefoundAuditService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "退款审核-批量删除")
    @ApiOperation(value = "退款审核-批量删除", notes = "退款审核-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.registerRefoundAuditService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "退款审核-通过id查询")
    @ApiOperation(value = "退款审核-通过id查询", notes = "退款审核-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        RegisterRefoundAudit registerRefoundAudit = registerRefoundAuditService.getById(id);
        if (registerRefoundAudit == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(registerRefoundAudit);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param registerRefoundAudit
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, RegisterRefoundAudit registerRefoundAudit) {
        return super.exportXls(request, registerRefoundAudit, RegisterRefoundAudit.class, "退款审核");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, RegisterRefoundAudit.class);
    }


    /**
     * 审核中
     *
     * @param status，id
     * @return
     */
    @AutoLog(value = "退款审核")
    @ApiOperation(value = "退款审核", notes = "退款审")
    @RequestMapping(value = "/audit")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> audit(@RequestParam String id,String status, String reason) {
        //获取登录人信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //运营审批realname 0-申请退款，1-运营审核同意，2-运营审核驳回，3-财务审核通过，4-财务审核驳回，5-完成退款
        RegisterRefoundAudit registerRefoundAudit = registerRefoundAuditService.getById(id);
        if (sysUser.getOrgCode().equals("A01A03")) {
            //运营审批通过
            if ("1".equals(status)) {
                registerRefoundAudit.setOperateName(sysUser.getRealname());
                registerRefoundAudit.setOperateAudit("运营审批");
                registerRefoundAudit.setStatus(1);
            }
            //运营审批失败.
            if ("2".equals(status)) {
                registerRefoundAudit.setOperateName(sysUser.getRealname());
                registerRefoundAudit.setOperateAudit("运营审批");
                registerRefoundAudit.setStatus(2);
                registerRefoundAudit.setOperateReason(reason);
            }
            registerRefoundAudit.setOperateTime(new Date());
        } else if (sysUser.getOrgCode().equals("A01A04")) {
            //财务营审批通过
            if ("1".equals(status)) {
                registerRefoundAudit.setFinancialAudit("财务审批");
                registerRefoundAudit.setFinancialName(sysUser.getRealname());
                registerRefoundAudit.setStatus(3);
            }
            //财务审批失败
            if ("2".equals(status)) {
                registerRefoundAudit.setStatus(4);
                registerRefoundAudit.setFinancialReason(reason);
            }
            registerRefoundAudit.setFinancialTime(new Date());
        } else {
            return Result.error("无审批权限，请联系运营或财务审批！!");
        }


        //退款金额并推送退款信息
        if (registerRefoundAudit.getStatus() == 3) {
            try {
                String relationId = registerRefoundAudit.getRelationId();
                DoctorRegisterRecord doctorRegisterRecord = doctorRegisterRecordService.getById(relationId);
                LambdaQueryWrapper<WxUserinfo> query = Wrappers.lambdaQuery();
                query.eq(WxUserinfo::getOpenid, registerRefoundAudit.getOpenid());
                log.info(registerRefoundAudit.getOpenid());
                WxUserinfo wxUserinfo = wxUserinfoService.getOne(query); //获取微信用户
                RegisterPayOrder payOrder = new RegisterPayOrder();
                payOrder.setDoctorId(registerRefoundAudit.getDoctorId());
                payOrder.setRelationId(registerRefoundAudit.getRelationId());
                payOrder.setStatus(RegisterEnum.OPERATE.getCode());
                payOrder.setPatientId(doctorRegisterRecord.getPatientId());
//                payOrder.setWxUserinfoId(wxUserinfo.getId());
                doctorRegisterRecord.setPatientId(doctorRegisterRecord.getPatientId());
                RegisterPayOrder registerPayOrder = registerPayOrderService.getByRelationId(payOrder);
                //更新订单状态
                registerPayOrder.setStatus(3);
                registerPayOrder.setOrderType(2);
                registerPayOrderService.updateById(registerPayOrder);
                //释放号源
                doctorRegisterRecord.setStatus(RegisterEnum.REFOUD.getCode());
                doctorRegisterRecordService.updateById(doctorRegisterRecord);
                wxRefundService.refundNew(registerPayOrder.getAmount() + "", registerPayOrder.getThirdOrderCode());
                registerRefoundAudit.setStatus(5);
            } catch (WeixinPayException e) {
                e.printStackTrace();
            }
        }
        registerRefoundAuditService.updateById(registerRefoundAudit);
        return Result.ok("编辑成功!");
    }
}
